<template>
  <div class="menu">

    <div class="btns">
      <el-button type="primary" @click="dialogVisible = true">添加</el-button>
      <el-button type="primary">全部展开</el-button>
      <el-button type="primary">全部折叠</el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :data="menuPermissions"
      style="width: 100%; margin-bottom: 20px"
      row-key="id"
      border
      default-expand-all
    >
      <template #empty>
        <el-empty description="暂无数据" />
      </template>
      <el-table-column prop="name" label="名称" />
      <el-table-column prop="type" label="类型">
        <template #default="{row}">
          <span>{{ row.type === 1 ? '菜单(页面)' : '功能(按钮)' }}</span>
          <!-- <span v-if="row.type === 1">菜单(页面)</span>
          <span v-else>功能(按钮)</span> -->
        </template>
      </el-table-column>
      <el-table-column prop="rule" label="规则" />
      <el-table-column prop="icon" label="操作">
        <template #default="{row}">
          <el-button type="primary" size="small" @click="handleEditMenuPermission(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteMenuPermission(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加与修改的对话框 -->
    <el-dialog v-model="dialogVisible" :title="(permissionItem.id ? '修改' : '添加') + '菜单权限'" width="500">
      <el-form :model="permissionItem" label-width="80px" label-suffix=":">
        <el-form-item label="父级菜单">
          <el-tree-select
            v-model="permissionItem.pid"
            :data="parentMenus"
            check-strictly
            clearable
            :render-after-expand="false"
            placeholder="请选择父级菜单, 不选择则为顶级菜单"
          >
            <!-- <template #default="{ data: { name } }">
              {{ name }}
            </template> -->
          </el-tree-select> 
          <!-- <el-select v-model="permissionItem.pid" placeholder="请选择父级菜单">
            <el-option label="Zone No.1" value="shanghai" />
            <el-option label="Zone No.2" value="beijing" />
          </el-select> -->
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="permissionItem.name" placeholder="请输入权限名称"></el-input>
        </el-form-item>
        <el-form-item label="类型">
          <el-radio-group v-model="permissionItem.type">
            <el-radio :value="1">菜单(页面)</el-radio>
            <el-radio :value="2">功能(按钮)</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="规则">
          <el-input v-model="permissionItem.rule" placeholder="请输入权限规则"></el-input>
        </el-form-item>
        <el-form-item  label="排序">
          <el-input v-model="permissionItem.order" placeholder="请输入菜单排序"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="permissionItem.status" active-text="启用" inactive-text="禁用" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveMenuPermission">
            {{ permissionItem.id ? '修改' : '添加' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import {
  getAllMenuPermissions,
  addMenuPermission,
  updateMenuPermission,
  deleteMenuPermission,
} from '@/api/menu-permission'
import { ElMessageBox } from 'element-plus'
import { transToTree } from '@/utils/index'

// 所有菜单权限原始数据
const originPermissions = ref<IPermission[]>([])

// 所有的菜单权限树形数据
const menuPermissions = ref<IPermission[]>([])

// 查询所有菜单权限数据
const loadMenuPermissions = async () => {
  const res = await getAllMenuPermissions()
  originPermissions.value = res.list
  // 将查询到的权限数据转为树形结构
  const tree = transToTree(res.list)
  menuPermissions.value = tree
}
loadMenuPermissions()

// 编辑权限对话框显隐状态
const dialogVisible = ref<boolean>(false)
// 编辑对话框中的表单数据
const permissionItem = ref<IPermission>({
  id: '',
  pid: '',
  name: '',
  type: 1,
  rule: '',
  icon: '',
  status: true,
})

// 在树形选择框中的数据（父级菜单）结构
const parentMenus = computed(() => {
  // 筛选出原始数据中所有菜单级权限数据
  let menus: any = originPermissions.value.filter(item => item.type === 1)
  // 修改数据的结构
  menus = menus.map((menu: any) => {
    return {
      pid: menu.pid,
      id: menu.id,
      value: menu.id,
      label: menu.name,
    }
  })
  // 转树形结构
  const tree = transToTree(menus)
  console.log('树形选择器:', tree)
  return tree
})

// 重置表单中的数据
const resetPermissionItem = () => {
  permissionItem.value = {
    id: '',
    pid: '',
    name: '',
    type: 1,
    rule: '',
    icon: '',
    status: true,
  }
}

// 监听对话框的显隐状态，如果关闭了，就重置表单数据
watch(dialogVisible, (newValue) => {
  if (!newValue) {
    resetPermissionItem()
  }
})

/**
 * 点击编辑(修改)按钮，打开编辑对话框，回显表单数据
 */
const handleEditMenuPermission = (row: IPermission) => {
  // 打开对话框
  dialogVisible.value = true
  // 回显表单数据
  permissionItem.value = { ...row }
}

/**
 * 保存表单中提交的菜单权限数据
 */
const handleSaveMenuPermission = async() => {
  // console.log('表单接收到:', permissionItem.value)

  // 根据表单数据中是否存在 id 决定是添加还是修改
  if (permissionItem.value.id) {
    // 修改
    await updateMenuPermission(permissionItem.value)
  } else {
    // 发送网络请求，添加
    await addMenuPermission(permissionItem.value)
    // console.log('添加结果:', result)
  }

  // 关闭对话框
  dialogVisible.value = false
  // 重新加载菜单权限数据
  loadMenuPermissions()
}

/**
 * 处理点击删除按钮，显示确认对话框
 */
const handleDeleteMenuPermission = async (row: IPermission) => {
  try {
    // 显示确认对话框
    const confirmResult = await ElMessageBox.confirm('确定要删除该菜单权限吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    // console.log('用户确认删除结果:', confirmResult)
    // 如果用户确认删除，就发送网络请求，删除数据
    if (confirmResult === 'confirm') {
      await deleteMenuPermission(row.id)
      // 重新加载菜单权限数据
      loadMenuPermissions()
    }
  } catch (error) {
    console.log('点击取消...', error)
  }
}
</script>

<style lang="scss" scoped>
.menu {
  padding: 12px;

  .btns {
    margin-bottom: 12px;
  }
}
</style>
